//
//  BHChoseFunAddressViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/6/25.
//

import UIKit
protocol BHChoseFunAddressViewControllerDelegate {
    func didSelectRelateModel(model: BHFunPublishRelateModel)
}

class BHChoseFunAddressViewController: BHBaseViewController {
    var delegate: BHChoseFunAddressViewControllerDelegate?
    
    
    lazy var headerView: BHChosePlaceHeaderView = {
        let view = BHChosePlaceHeaderView.loadFromXib()
        view.frame = CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: BHChosePlaceHeaderView.bottomHeight)
        return view
    }()
    
    lazy var tableView: UITableView = {
        let view = UITableView.buildTableView(style: .grouped)
        view.frame = CGRect(x: 0, y: UIScreen.begainY+BHChosePlaceHeaderView.bottomHeight, width: UIScreen.width, height: UIScreen.showHeight-BHChosePlaceHeaderView.bottomHeight)
        view.delegate = self
        view.dataSource = self
        view.regiseterNib(nibName: "BHChosePlaceInfoCell")
        return view
    }()
    

    fileprivate var type: Int = 1
    fileprivate var relateArray: [BHFunPublishRelateModel] = []
    fileprivate var searchKey: String = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.bh_navigationBar.title_label.text = "选择场馆"
        
        self.view.addSubview(self.headerView)
        self.view.addSubview(self.tableView)
        
        self.queryRelateService()

        self.headerView.changeToIndexBlock = { [weak self] indexType in
            self?.type = indexType
            self?.page = 1
            self?.relateArray.removeAll()
            
            self?.queryRelateService()
        }
        
        self.headerView.goSearchingBlock = { [weak self] text in
            self?.searchKey = text
            self?.page = 1
            self?.queryRelateService()
        }
        
        self.tableView.addRefresh { [weak self] in
            self?.page = 1
            self?.queryRelateService()
        }
        
        self.tableView.addloadMore { [weak self] in
            self?.page += 1
            self?.queryRelateService()
        }
        
    }
}
extension BHChoseFunAddressViewController: UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.relateArray.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
       return 82
    }
    
}

extension BHChoseFunAddressViewController: UITableViewDelegate {
 
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "BHChosePlaceInfoCell", for: indexPath) as! BHChosePlaceInfoCell
        let model = self.relateArray[indexPath.row]
        cell.model = model
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.relateArray[indexPath.row]

        self.delegate?.didSelectRelateModel(model: model)
        self.navigationController?.popViewController(animated: true)
    }
}


extension BHChoseFunAddressViewController {
    func queryRelateService()  {
        let dic = self.appendDic()
        
        let manager = BHHTTPClient.init()
        manager.get(url: String.fun_publish_relate_url, paramters: dic) { (success, errorMsg, responseDic) in
            self.tableView.endRefresh()
            self.tableView.endLoading()
            
            if success == true {
                let result = BHJsonTool.decodeDicFromDic(dic: responseDic, key: "result")
                let total = BHJsonTool.decodeIntFromDic(dic: result, key: "total")

                if self.page == 1 {
                    self.tableView.endLoadWithNoMoreData(false)
                    if self.relateArray.count != 0 {
                        self.relateArray.removeAll()
                    }
                }
                
                let record = BHJsonTool.decodeArrayFromDic(dic: result, key: "records")
                for dic in record {
                    let model = BHFunPublishRelateModel.init()
                    model.parseDic(dic: dic as! [String : Any])
                    self.relateArray.append(model)
                }
                self.tableView.reloadData()
                if self.relateArray.count >= total {
                    self.tableView.endLoadWithNoMoreData(true)
                }
                    
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
        
    }
    
    func appendDic() -> [String:Any] {
        var dic: [String:Any] = [:]
        dic["pageNo"] = self.page
        dic["pageSize"] = 20
        dic["relationType"] = 1
        dic["search"] = self.searchKey
        dic["longitude"] = BHLocationManager.shared.longitude
        dic["latitude"] = BHLocationManager.shared.latitude
        dic["type"] = self.type
        dic["search"] = self.searchKey

        return dic
    }
}
